package org.road0329.dlt698.asn1.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;

import java.io.IOException;

public class AxdrOptional<T extends AxdrType> {
    private T value = null;
    private boolean usage = false;

    public AxdrOptional(T value, boolean usage) {
        if (value == null) {
            throw new IllegalArgumentException("Value cannot be null");
        }
        this.value = value;
        this.usage = usage;
    }

    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        AxdrBoolean axdrUsage = new AxdrBoolean();
        codeLength += axdrUsage.decode(input);
        this.usage = axdrUsage.getVal();
        if (this.usage) {
            codeLength += this.value.decode(input);
        }
        return codeLength;
    }

    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength = 0;
        if (this.usage) {
            if (this.value != null) {
                codeLength += this.value.encode(output);
            } else {
                throw new IllegalStateException("value is null");
            }
        }
        AxdrBoolean usage = new AxdrBoolean();
        usage.setVal(this.usage);
        codeLength += usage.encode(output);
        return codeLength;
    }

    public void setUsed(boolean use) {
        this.usage = use;
    }

    public boolean isUsed() {
        return this.usage;
    }

    public T getValue() {
        if (this.value != null) {
            return this.value;
        } else {
            throw new IllegalStateException("value is null");
        }
    }

    public void setValue(T value) {
        this.usage = value != null;
        this.value = value;
    }

    @Override
    public String toString() {
        if (this.usage) {
            if (this.value != null) {
                return this.value.toString();
            } else {
                throw new IllegalStateException("value is null");
            }
        } else {
            return "not set";
        }
    }
}



